<template>
  <div>
    <ListTab v-model="activeId" :tabs="tabList" :show-header="!showMobilePage" is-table />
    <div v-loading="loading" :class="{'mobile-setting-page mobile-el-dialog-form': showMobilePage}" class="page-list">
      <GlobalSetting v-if="activeId === '全局设置'" :field-items="getFieldItems('全局设置')" :default-expanded-keys="defaultExpandedKeys" @getData="getData" />
      <orderSetting v-if="activeId === '订单管理'" :field-items="getFieldItems('订单管理')" :default-expanded-keys="defaultExpandedKeys" @getData="getData" />
      <div v-if="activeId === '财务管理'" class="page-list-item full-height mobile-setting-radius" style="padding-top:5px;padding-bottom:5px;">
        <fieldTree :field-items="getFieldItems('财务管理')" :default-expanded-keys="defaultExpandedKeys" status-required @getData="getData" />
      </div>
      <CustomerSetting v-if="activeId === '客户管理'" :field-items="getFieldItems('客户管理')" :default-expanded-keys="defaultExpandedKeys" @getData="getData"/>
      <resourceSetting v-if="activeId === '资源管理'" :field-items="getFieldItems('资源管理')" :default-expanded-keys="defaultExpandedKeys" @getData="getData"/>
      <businessAnalysis v-if="activeId === '经营分析'" :field-items="getFieldItems('经营分析')" :default-expanded-keys="defaultExpandedKeys" @getData="getData" />
      <div v-if="activeId === '发票管理'" class="page-list-item full-height mobile-setting-radius" style="padding-top:5px;padding-bottom:5px;">
        <InvoiceManage :field-items="getFieldItems('发票管理')" :default-expanded-keys="defaultExpandedKeys" @getData="getData" />
      </div>
      <div v-if="activeId === '合同管理'" class="page-list-item full-height mobile-setting-radius" style="padding-top:5px;padding-bottom:5px;">
        <fieldTree :field-items="getFieldItems('合同管理')" :default-expanded-keys="defaultExpandedKeys" @getData="getData" />
      </div>
      <div v-if="activeId === '供应商管理'" class="page-list-item full-height mobile-setting-radius" style="padding-top:5px;padding-bottom:5px;">
        <fieldTree
          :field-items="getFieldItems('供应商管理')"
          :default-expanded-keys="defaultExpandedKeys"
          :add-auth="hasRouteAuth('auth:system:supplierAdd')"
          :edit-auth="hasRouteAuth('auth:system:supplierEdit')"
          :del-auth="hasRouteAuth('auth:system:supplierDelete')"
          @getData="getData" />
      </div>
      <div v-if="activeId === '成本管理'" class="page-list-item full-height mobile-setting-radius" style="padding-top:20px;padding-bottom:20px;">
        <costComponent :hide-title="true" :show-order-setting="false" />
      </div>
      <div v-if="activeId === '标签管理'" class="full-height mobile-setting-radius">
        <tagComponent />
      </div>
      <div v-if="activeId === '萌力星球'" class="page-list-item full-height mobile-setting-radius" style="padding-top:20px;padding-bottom:20px;">
        <mengliModule
          :field-items="getFieldItems('萌力星球')"
          :default-expanded-keys="defaultExpandedKeys"
          :notify-users="notifyUsers"
          @getData="getData"
          @storeNotifyUsersCallback="queryNotifyUsers"/>
      </div>
      <div v-if="activeId === '运营管理'" class="page-list-item full-height mobile-setting-radius" style="padding-top:9px;padding-bottom:20px;">
        <operateModule />
      </div>
    </div>
  </div>
</template>

<script>
import { getSettingList } from '@/api/setting';
import { hasRouteAuth } from '@/utils/permission';
// import ElMessage from '@/utils/message';
// 组件
import ListTab from '@/components/ListTab';
import orderSetting from './settingModule/orderSetting';
import resourceSetting from './settingModule/resourceSetting';
import businessAnalysis from './settingModule/businessAnalysis';
import mengliModule from './settingModule/mengliModule';
import InvoiceManage from './settingModule/invoiceManage';
import CustomerSetting from './settingModule/customerSetting';
import fieldTree from '@/components/SettingPage/fieldTree';
import costComponent from '@/components/Configuration/costComponent';
import GlobalSetting from './settingModule/globalSetting';
import operateModule from './settingModule/operateModule';
import tagComponent from './settingModule/tagComponent';
import { getNotifyUsers } from '@/api/setting';
import { mapState } from 'vuex';

export default {
  components: { ListTab, fieldTree, orderSetting, GlobalSetting, InvoiceManage,
    resourceSetting, businessAnalysis, costComponent, mengliModule, operateModule, CustomerSetting, tagComponent },
  data() {
    return {
      fieldData: [],
      loading: false,
      isInit: true,
      activeId: '',
      tabList: [],
      notifyUsers: [],
      defaultExpandedKeys: [],
      defaultTabList: [ // 默认tab，getSettingList 接口无权限时展示
        { id: 0, name: '全局设置' },
        { id: 1, name: '订单管理' },
        { id: 2, name: '财务管理' },
        { id: 3, name: '客户管理' },
        { id: 4, name: '资源管理' },
        { id: 5, name: '经营分析' },
        { id: 6, name: '发票管理' },
        { id: 7, name: '合同管理' },
        { id: 8, name: '萌力星球' },
        { id: 10, name: '供应商管理' }
      ]
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  watch: {
    activeId: {
      handler(val) {
        val === '萌力星球' && this.queryNotifyUsers();
      },
      immediate: true
    }
  },
  created() {
    this.getData();
  },
  methods: {
    hasRouteAuth,
    /** 数据获取 */
    getData(respetPid) {
      this.loading = true;
      this.defaultExpandedKeys = [];
      getSettingList({ notShowNoAuthTip: true }).then(res => {
        this.loading = false;
        if (res.code === 200 && res.data) {
          // pid为唯一id
          res.data.forEach(i => {
            i.pid = i.id;
            if (i.item && i.item.length > 0) {
              i.item.forEach(j => {
                j.pid = i.id + '-' + j.id;
                this.setLevel(j, j.level, j.pid);
              });
            }
            if (i.name === '全局设置') {
              this.handelLabelData(i.item);
            }
            if (i.name === '客户管理') {
              this.handleCustomFormat(i.item);
            }
          });
          this.fieldData = res.data;
          this.getTabList(res.data, this.isInit);
          this.isInit = false;
          if (respetPid && respetPid.length > 0) this.defaultExpandedKeys = respetPid;
        }
      }).catch((e) => {
        if (e.code && e.code === 403) {
          this.getTabList(this.defaultTabList, this.isInit);
        }
        this.loading = false;
        this.isInit = false;
      });
    },
    setLevel(items, level, pid) {
      if (items.item && items.item.length > 0) {
        items.item.forEach(i => {
          // 平台字段配置不手动设置level
          if (!i.fieldSetting) {
            i.level = level;
          }
          i.pid = pid + '-' + i.id;
          if (i.item && i.item.length > 0) {
            this.setLevel(i, level, i.pid);
          }
        });
      }
    },
    getTabList(list, init = false) {
      const tabList = [];
      list.forEach(i => {
        if (i.name !== '全局设置' && this.hasModule(i.name)) {
          tabList.push({ id: i.name, name: i.name });
        }
      });
      if (hasRouteAuth('system:cost:read')) {
        tabList.push({ id: '成本管理', name: '成本管理' });
      }
      if (!hasRouteAuth('auth:system:mengli')) {
        tabList.push({ id: '萌力星球', name: '萌力星球' });
      }
      if (hasRouteAuth('auth:system:global')) {
        tabList.unshift({ id: '全局设置', name: '全局设置' });
      }
      if (hasRouteAuth('system:operate:read')) {
        tabList.push({ id: '运营管理', name: '运营管理' });
      }
      if (tabList.length > 0 && init) {
        this.activeId = tabList[0].id;
      }
      tabList.push({ id: '标签管理', name: '标签管理' });
      this.tabList = tabList;
    },
    getFieldItems(name) {
      const findRes = this.fieldData.find(i => i.name === name);
      if (findRes && findRes.item) {
        return findRes.item;
      }
      return [];
    },
    /** 权限判断 */
    hasModule(name) {
      let type = '';
      switch (name) {
        case '订单管理':
          type = 'order';
          break;
        case '财务管理':
          type = 'finance';
          break;
        case '客户管理':
          type = 'client';
          break;
        case '资源管理':
          type = 'resource';
          break;
        case '经营分析':
          type = 'total';
          break;
        case '发票管理':
          type = 'receipt';
          break;
        case '合同管理':
          type = 'contract';
          break;
        case '萌力星球':
          type = 'mengli';
          break;
        case '供应商管理':
          type = 'supplier';
          break;
      }
      return hasRouteAuth(`auth:system:${type}`);
    },
    getRoot(node) {
      if (!node) return null;
      if (node.level === 1) {
        return node;
      }
      return this.getRoot(node.parent);
    },
    handelLabelData(list) {
      const tags = list.find(i => i.name === '标签管理');
      if (!tags) return [];
      if (tags.item) {
        tags.item.forEach(i => {
          if (i.item && i.item.length > 0) {
            if (!i.item[0].tagsList) {
              const tagsList = JSON.parse(JSON.stringify(i.item));
              tagsList[0].tagsList = tagsList;
              i.item = [{
                name: '',
                id: '',
                tagsList: tagsList
              }];
            }
          } else {
            i.item = [{
              name: '', id: '', tagsList: []
            }];
          }
        });
      }
      return [tags];
    },
    // 客户管理数据初始化format
    handleCustomFormat(data) {
      data.forEach(fieldItem => {
        if (fieldItem.id === 4) { // 客户状态
          (fieldItem.item || []).forEach(i => { i.parentId = 4; });
        }
        if (fieldItem.id === 29) { // 客户等级
          (fieldItem.item || []).forEach(i => {
            if (i.levelPost && typeof i.levelPost === 'string') {
              i.levelPost = i.levelPost.split(',').map(name => {
                return { id: name, name: name };
              });
            }
          });
        }
      });
    },
    // 库存预警通知人员
    queryNotifyUsers() {
      getNotifyUsers().then(res => {
        if (res.code === 200) {
          res.data && res.data.forEach(user => {
            user.userName = user.name;
          });
          this.notifyUsers = res.data || [];
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page-list {
  margin: 16px;
  .page-list-item {
    // box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
    // border-radius:12px;
    background-color: #fff;
    padding: 24px;
  }
}
.full-height {
  min-height: calc(100vh - 80px);
}
.mobile-setting-page {
  margin: 12px;
  ::v-deep {
    .global-setting-item {
      padding: 12px;
    }
    .mobile-setting-radius {
      border-radius: 6px;
      padding: 12px;
    }
    .mobile-link-btn {
      font-size: 14px;
      font-family: PingFang SC, PingFang SC-Medium;
      font-weight: bold;
      text-align: left;
      color: #406eff;
      line-height: 11px;
    }
    .mobile-btn-left {
      position: relative;
      padding-left:12px;
      margin-left: 12px;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -7px;
        width: 1px;
        background: #ddd;
        height: 14px;
      }
    }
    .el-tree {
      .el-tree-node__children {
        overflow-x: auto;
      }
      .tree-main {
        .el-input {
          width: 100% !important;
          .el-input__inner {
            width: 100% !important;
          }
        }
      }
    }
  }
}
</style>
